package com.yangrd.airship.sys.web.config;

import cn.dev33.satoken.stp.StpUtil;
import com.yangrd.airship.common.utils.PrincipalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * description: LogHandlerInterceptor
 *
 * @author: yangrd
 * @date: 2021/2/5
 * @version: 1.0
 */
@Slf4j
public class LogHandlerInterceptor implements HandlerInterceptor {

    private static final ThreadLocal<Long> START_TIME_THREAD_LOCAL = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        START_TIME_THREAD_LOCAL.set(System.currentTimeMillis());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        Long startTime = START_TIME_THREAD_LOCAL.get();
        START_TIME_THREAD_LOCAL.remove();
        Long endTime = System.currentTimeMillis();
        if (Objects.nonNull(startTime)) {
            Long executeUseMillisecond = endTime - startTime;
            if (StpUtil.isLogin()) {
                log.debug("currentUser: [userId: {}, username: {}] url: {} methods:{} 请求处理用时 {}ms", PrincipalUtils.getCurrentUserId(), PrincipalUtils.getCurrentUsername(), request.getRequestURI(), request.getMethod(), executeUseMillisecond);
            } else {
                log.debug("currentUser: anonymous url: {} methods:{} 请求处理用时 {}ms", request.getRequestURI(), request.getMethod(), executeUseMillisecond);
            }
        }
    }
}
